import router, { asyncRouters } from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import { Message } from 'element-ui'
import { getUserInfoTypeAPI } from './api'

const whiteList = ['/login', '/404']

router.beforeEach(async (to, from, next) => {
  NProgress.start()

  const path = to.path

  if (store.getters.token) {
    if (path === '/login') {
      // 登陆了 -> 不能去登录页
      next('/')
      Message.error('已登录不能前往登录页')
      NProgress.done()
    } else {
      next()
      if (!store.getters.name) {
        try {
          const { success } = await store.dispatch('user/getUserInfoActions')
          if (!success) {
            store.commit('user/REMOVE_TOKEN')
            store.commit('user/RESET_STATE')
            router.push('/login')
            return false
          }

          const routerList =
            asyncRouters[(await getUserInfoTypeAPI()).data.type]
          for (const r in routerList) {
            router.addRoute(routerList[r])
          }
          router.addRoute({
            path: '*',
            redirect: '/404',
            hidden: true
          })
          store.commit('permission/setRoutes', routerList)
          next({
            path: to.path,
            replace: true
          })
        } catch (err) {
          return console.dir(err)
        }
      }
    }
  } else {
    // 没登陆 -> 只能去白名单页
    if (whiteList.includes(path)) next()
    else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  if (to.name) window.document.title = to.meta.title + '-校园报修平台'
  NProgress.done()
})
